﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Servico;

// TODO falta as mensagens de erro e sucesso
public partial class RegistarTarefas : System.Web.UI.Page
{
    Service1 servico = new Service1();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Email"] != null)
        {
            DataTable dttblData = new DataTable();
            dttblData.TableName = "TarefasPendentesTecnico";
            //Response.Write(DateTime.Now.ToString());
            dttblData = servico.tarefasPendentesTecnico(Session["Email"].ToString(), DateTime.Now);
            
            // Array de registos
            DataRow[] dataRows = null;
            if (dttblData != null)  dataRows = dttblData.Select();
            if (dttblData != null && dataRows.Length != 0)
            {
                generateTable(dataRows);
            }
            else
                Session["Erro"] = "Não existem mais tarefas por registar!";
            }
        else
        {
            Session["Erro"] = "Por favor autentique-se!";
            Response.Redirect("Home.aspx");
        }

        MensagemErro();
    }

    protected DataTable criaDataTable(string[] campos)
    {
        DataTable myDataTable = new DataTable();
        DataColumn myDataColumn = new DataColumn();

        myDataColumn = new DataColumn();
        myDataColumn.ColumnName = "id_pedidos_recebidos";
        myDataColumn.DataType = System.Type.GetType("System.Int32");
        myDataTable.Columns.Add(myDataColumn);

        myDataColumn = new DataColumn();
        myDataColumn.ColumnName = "id_tarefa";
        myDataColumn.DataType = System.Type.GetType("System.Int32");
        myDataTable.Columns.Add(myDataColumn);

        myDataColumn = new DataColumn();
        myDataColumn.ColumnName = "designacao_tarefa";
        myDataColumn.DataType = System.Type.GetType("System.String");
        myDataTable.Columns.Add(myDataColumn);

        myDataColumn = new DataColumn();
        myDataColumn.ColumnName = "hora_inicio";
        myDataColumn.DataType = System.Type.GetType("System.DateTime");
        myDataTable.Columns.Add(myDataColumn);

        myDataColumn = new DataColumn();
        myDataColumn.ColumnName = "hora_fim";
        myDataColumn.DataType = System.Type.GetType("System.DateTime");
        myDataTable.Columns.Add(myDataColumn);

        return myDataTable;
    }

    protected void insereNaGridView(DataTable myDataTable, DataRow row, GridView gridView)
    {
        DataRow dataRow = myDataTable.NewRow();
        for (int i = 0; i < row.ItemArray.Length;i++ )
            dataRow[i] = row[i];
        //dataRow["data"] = row["data"];

        myDataTable.Rows.Add(dataRow);

        gridView.DataKeyNames = new string[] { "id_pedidos_recebidos", "id_tarefa" };
        gridView.DataSource = myDataTable;
        gridView.DataBind();
    }

    private void generateTable(DataRow[] dataRows)
    {
        //Cria a tabela e adiciona-a ao painel
        Table table = new Table();
        table.ID = "Table1";
        panelTarefasRealizadas.Controls.Add(table);

        // O numero de colunas e linhas a ser geradas
        const int colsCount = 2;
        int rowsCount = 0;
        if (dataRows != null)  rowsCount = dataRows.Length; 
        // Campos a mostar na tabela
        string[] campos = new string[] { "id_pedidos_recebidos", "id_tarefa", "designacao_tarefa", "hora_inicio", "hora_fim" };
        string[] headerText = new string[] { "Id Pedidos Recebidos", "Id Tarefa", "Designacao da tarefa", "Hora de Inicio", "Hora de Fim" };

        // Percorre a tabela e adiciona as tarefas e checkboxes
        for (int i = 0; i < rowsCount; i++)
        {
            TableRow row = new TableRow();
            for (int j = 0; j < colsCount; j++)
            {
                TableCell cell = new TableCell();

                if (j == 0) // primeira coluna
                {
                    // Cria GridView
                    GridView gridView = new GridView();
                    gridView.ID="GridViewRow_" + i + "Col_" + j;
                    gridView.AutoGenerateColumns = false;
                    gridView.Width = 550;

                    // cria colunas para a GridView
                    BoundField boundField = new BoundField();
                    for (int k = 0; k < campos.Length; k++)
                    {
                        boundField = new BoundField();
                        boundField.DataField = campos[k];
                        boundField.HeaderText = headerText[k];
                        gridView.Columns.Add(boundField);
                    } 

                    // insere na gridView
                    insereNaGridView(criaDataTable(campos), dataRows[i], gridView);
                    // Adiciona a gridVIew à TableCell
                    cell.Controls.Add(gridView);
                    // Adiciona a TableCell à TableRow
                    row.Cells.Add(cell);
                }
                else
                {
                    // Cria a checkbox
                    CheckBox cb = new CheckBox();
                    cb.ID = "CheckBoxRow_" + i + "Col_" + j;
                    // Adiciona à celula correspondente
                    cell.Controls.Add(cb);
                    // Adiciona a celula a linha da tabela
                    row.Cells.Add(cell);
                }
            }

            // Adiciona a linha à tabela
            table.Rows.Add(row);
            if (i == (rowsCount - 1))
            {
                panelSubmeter.Visible = true;
                //Response.Write("Aqui");
                //Literal lit = new Literal();
                //lit.Text = "<asp:Button ID=\"buttonSubmeter\" runat=\"server\" Text=\"Submeter\" onclick=\"buttonSubmeter_Click\" />";
                //panelSubmeter.Controls.Add(lit);
            }
        }

        //if (rowsCount != 0)
        //{
        //    TableRow rowLB = new TableRow();
        //    TableCell cellLB = new TableCell();
        //    rowLB.Cells.Add(cellLB); // first cell is empty
        //    cellLB = new TableCell();

        //    LinkButton lb = new LinkButton();
        //    lb.ID = "lbAll";
        //    lb.Text = "Select All";
        //    lb.OnClientClick = "lbAll_Click";
        //    cellLB.Controls.Add(lb);
        //    rowLB.Cells.Add(cellLB);

        //    lb = new LinkButton();
        //    lb.ID = "lbNone";
        //    lb.Text = "Select None";
        //    lb.OnClientClick = "lbNone_Click";
        //    cellLB.Controls.Add(lb);
        //    rowLB.Cells.Add(cellLB);

        //    table.Rows.Add(rowLB);
        //}

        //Set Previous Data on PostBacks
        //SetPreviousData(rowsCount, colsCount);

        //Sore the current Rows Count in ViewState
        //rowsCount++;
        //ViewState["RowsCount"] = rowsCount;
    }

    private void GetSelectedRows()
    {
        //Response.Write("entrou");
        bool sucesso = true;
        Table table = (Table)panelTarefasRealizadas.FindControl("Table1"); 
        if (table != null)
        {
            if (table.Rows.Count > 0)
            {
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    //Get the Checked value of the CheckBox using the Request objects
                    CheckBox check = (CheckBox)panelTarefasRealizadas.FindControl("CheckBoxRow_" + i + "Col_" + 1);
                    //Extract the CheckBox Control from within the Table
                    if (check.Checked) //If selected
                    {
                        GridView grid = (GridView)panelTarefasRealizadas.FindControl("GridViewRow_" + i + "Col_" + 0);
                        GridViewRow row = grid.Rows[0];
                        if (!servico.registarTarefasRealizadasTecnico(Session["Email"].ToString(),
                                                                        Convert.ToInt32(row.Cells[0].Text.ToString()),
                                                                        Convert.ToInt32(row.Cells[1].Text.ToString()),
                                                                        row.Cells[2].Text.ToString(),
                                                                        Convert.ToDateTime(row.Cells[4].Text.ToString())))    //Convert.ToDateTime(row.Cells[4].Text.ToString())
                        {
                            sucesso = false;
                        }
                        if (sucesso) Session["Sucesso"] = "O registo foi realizado com sucesso!";
                        else Session["Erro"] = "Não foi possível registar!";
                    }
                }
            }

            MensagemErro();
        }
    }


    protected void buttonSubmeter_Click(object sender, EventArgs e)
    {
        GetSelectedRows();
    }

    protected void buttonSelectAll_Click(object sender, EventArgs e)
    {
        Table table = (Table)panelTarefasRealizadas.FindControl("Table1");
        if (table != null && table.Rows.Count > 0)
        {
            for (int i = 0; i < table.Rows.Count; i++)
            {
                //Get the Checked value of the CheckBox using the Request objects
                CheckBox check = (CheckBox)panelTarefasRealizadas.FindControl("CheckBoxRow_" + i + "Col_" + 1);
                check.Checked = true;
            }
        }
    }

    protected void buttonUnselectAll_Click(object sender, EventArgs e)
    {
        Table table = (Table)panelTarefasRealizadas.FindControl("Table1");
        if (table != null && table.Rows.Count > 0)
        {
            for (int i = 0; i < table.Rows.Count; i++)
            {
                //Get the Checked value of the CheckBox using the Request objects
                CheckBox check = (CheckBox)panelTarefasRealizadas.FindControl("CheckBoxRow_" + i + "Col_" + 1);
                check.Checked = false;
            }
        }
    }

    protected void MensagemErro()
    {
        if (Session["Erro"] != null)
        {
            Literal lit = new Literal();
            lit.Text = "<ul id=\"menu2\"><li>" + Session["Erro"].ToString() + "</li></ul>";
            PanelMsg.Controls.Add(lit);
            Session["Erro"] = null;
        }
        if (Session["Sucesso"] != null)
        {
            Literal lit = new Literal();
            lit.Text = "<ul id=\"menu3\"><li>" + Session["Sucesso"].ToString() + "</li></ul>";
            PanelMsg.Controls.Add(lit);
            Session["Sucesso"] = null;
        }
    }
}